#include "salesrecordquery.h"
#include "ui_salesrecordquery.h"
#include <QMessageBox>
#include <QJsonArray>
#include <QStatusBar>
#include "../usermanager.h"
#include "mainwindow.h"


SalesRecordQueryWindow::SalesRecordQueryWindow(QWidget *parent)
    : QWidget(parent)
    , salesrecordquerywindowUi(new Ui::SalesRecordQueryWindow)
    , networkManager(new NetworkManager(this))
{
    salesrecordquerywindowUi->setupUi(this);
    salesrecordquerywindowUi->endDateEdit->setDate(QDate::currentDate());
    connect(networkManager, &NetworkManager::querySalesRecordsResponseReceived, this, &SalesRecordQueryWindow::handleQuerySalesRecordResponse);
}

SalesRecordQueryWindow::~SalesRecordQueryWindow()
{
    delete salesrecordquerywindowUi;
}

void SalesRecordQueryWindow::on_queryButton_clicked()
{
    QString medicineName = salesrecordquerywindowUi->medicineNameLineEdit->text();
    QString customer = (UserManager::instance().getRole() == UserManager::User)
                            ? UserManager::instance().getUsername() : "";
    QString startDate = salesrecordquerywindowUi->startDateEdit->date().toString(Qt::ISODate);
    QString endDate = salesrecordquerywindowUi->endDateEdit->date().toString(Qt::ISODate);

    if (medicineName.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "请填写药品名称。");
        return;
    }

    QJsonObject json;
    json["medicine_name"] = medicineName;
    json["username"] = customer;
    json["start_date"] = startDate;
    json["end_date"] = endDate;

    networkManager->querySalesRecords(json);
}

void SalesRecordQueryWindow::handleQuerySalesRecordResponse(const QJsonObject &response)
{
    int code = response.value("code").toInt();
    QString desc = response.value("desc").toString();

    if (code == 200) {
        QString dataString = response.value("data").toString();
        QJsonDocument jsonDoc = QJsonDocument::fromJson(dataString.toUtf8());
        if (!jsonDoc.isArray()) {
            if (UserManager::instance().getRole() == UserManager::User)
                MainWindow::getMainWindow()->statusBar()->showMessage("您没有过购买该商品。", 3000);
            else
                MainWindow::getMainWindow()->statusBar()->showMessage("该商品暂未被购买过。", 3000);
            return;
        }

        QJsonArray data = jsonDoc.array();
        salesrecordquerywindowUi->resultTable->setRowCount(0);

        for (int i = 0; i < data.size(); ++i) {
            QJsonObject record = data[i].toObject();

            int row = salesrecordquerywindowUi->resultTable->rowCount();
            salesrecordquerywindowUi->resultTable->insertRow(row);
            salesrecordquerywindowUi->resultTable->setItem(row, 0, new QTableWidgetItem(record.value("medicine_name").toString()));
            salesrecordquerywindowUi->resultTable->setItem(row, 1, new QTableWidgetItem(record.value("username").toString()));
            salesrecordquerywindowUi->resultTable->setItem(row, 2, new QTableWidgetItem(QString::number(record.value("quantity").toInt())));
            salesrecordquerywindowUi->resultTable->setItem(row, 3, new QTableWidgetItem(record.value("sale_date").toString()));
        }
    } else {
        QMessageBox::warning(this, "错误", "销售记录查询失败：" + desc);
    }
}
